<template>
    <div class="_fc_table_opt">
        <el-table
            :data="modelValue"
            border
            size="small"
            style="width: 100%">
            <template v-for="(col,idx) in column" :key="col.label + idx">
                <el-table-column :label="col.label">
                    <template #default="scope">
                        <el-input size="small" :modelValue="scope.row[col.key] || ''"
                                  @Update:modelValue="(n)=>(scope.row[col.key] = n, onInput(scope.row))"></el-input>
                    </template>
                </el-table-column>
            </template>
            <el-table-column min-width="50" align="center" fixed="right">
                <template #default="scope">
                    <i class="jd-icon icon-delete" @click="del(scope.$index)"></i>
                </template>
            </el-table-column>
        </el-table>
        <el-button link type="primary" @click="add" style="margin-top: 5px">
            <i class="jd-icon icon-add" style="margin-right: 5px;"></i> {{ t('tableOptions.add') }}
        </el-button>
    </div>
</template>

<script>
import {defineComponent} from 'vue';

export default defineComponent({
    name: 'TableOptions',
    inheritAttrs: false,
    props: {
        modelValue: [Object, Array, String]
    },
    inject: ['designer'],
    data() {
        return {
            //column: [{label: 'Label', key: 'label'}, {label: 'Value', key: 'value'}],
            column: [{label: '选项值', key: 'label'}],
            t: this.designer.setupState.t,
        };
    },
    created() {
        if (!Array.isArray(this.modelValue)) {
            this.$emit('input', []);
        }
    },
    methods: {
        onInput(item) {
            if (item.label) {
                this.input();
            }
        },
        input() {
            var options = this.modelValue;
            options.forEach(item =>{
                item.value = item.label
            })
            //this.$emit('update:modelValue', this.modelValue);
            this.$emit('update:modelValue', options);
        },
        add() {
            this.modelValue.push(this.column.reduce((initial, v) => {
                initial[v.key] = '';
                return initial;
            }, {}));
        },
        del(idx) {
            this.modelValue.splice(idx, 1);
            this.input(this.modelValue);
        }
    }
});
</script>

<style scoped>
._fc_table_opt {
    width: 100%;
}
</style>
